//
//  MypageSearchViewController.m
//  TTMusic
//
//  Created by yanghuiyan on 16/4/1.
//  Copyright © 2016年 cpy. All rights reserved.
//

#import "MypageSearchViewController.h"
#import "YHY_MyPageSearch_TVC.h"
#import "DataModel.h"
#import "MySearchDetailViewController.h"
#import "CPYSearchHistoryManager.h"

@interface MypageSearchViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UISearchBar *mySearchBar;

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, strong) TTMusicBaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSString *string;

@property (nonatomic, retain) NSArray *searchHistoryArray;

@property (nonatomic, retain) NSMutableArray *keywordHistoryArray;

@end

@implementation MypageSearchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    [self readNSUserDefaults];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [NSMutableArray array];

    // Do any additional setup after loading the view.
    
    [self creatview];
    [self dataRequest];
    
    // 热门搜索点击事件
    // 接受通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jump:) name:@"detail" object:nil];
    
}

#pragma mark - 热门搜索
- (void)jump:(NSNotification *)notifition {

    
    NSString *string = notifition.object;
    
    MySearchDetailViewController  *VC = [[MySearchDetailViewController alloc] init];
    
    VC.str = string;
    
    [self.navigationController pushViewController:VC animated:YES];
    
    [self.mySearchBar resignFirstResponder];

    
}
#pragma mark - creatView

- (void)creatview {
    
    //导航栏左侧按钮
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemAction:)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建searchBar
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(40, 20, SysWidth - 70, 40)];
    self.mySearchBar.placeholder = @"搜索单曲、歌手、专辑、歌单、MV";
    self.mySearchBar.delegate = self;
    self.navigationItem.titleView = _mySearchBar;
    
    // 设置搜索框
    self.mySearchBar.barStyle = UIBarStyleDefault;
    
    
    
    //创建tableView
    self.tableView = [[TTMusicBaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.tableView registerClass:[YHY_MyPageSearch_TVC class]forCellReuseIdentifier:@"MypageSearchTableViewCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
     // 给tableView加手势
//    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] init];
//    [backTap addTarget:self action:@selector(backTapAaction:)];
//    [self.tableView addGestureRecognizer:backTap];
}

//#pragma mark - backView手势
//- (void)backTapAaction:(UITapGestureRecognizer *)sender {
//    
//    [self.mySearchBar resignFirstResponder];
//    
//}

#pragma mark - 左侧按钮点击事件
- (void) leftItemAction:(UIBarButtonItem *)button {
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.tabBarController.tabBar.hidden = NO;
    [self.mySearchBar resignFirstResponder];
}

#pragma mark - 实现UISearchBarDelegate协议方法
// 当点击search的时候调用
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [CPYSearchHistoryManager SearchText:_mySearchBar.text];//缓存搜索记录

    
    [self.dataSource removeAllObjects];
    
    // 将搜索的文字存到字符串
    self.string = searchBar.text;
    
    MySearchDetailViewController  *VC = [[MySearchDetailViewController alloc] init];
    VC.str = self.string;
    [self.navigationController pushViewController:VC animated:YES];
    
//    self.page = 1;
//    [self.tableView addFooterWithTarget:self action:@selector(GETData)];
//    [self.tableView footerBeginRefreshing];
//    self.tableView.footerPullToRefreshText = @"加载更多";
//    self.tableView.footerRefreshingText = @"加载完成";
//    self.tableView.footerReleaseToRefreshText = @"正在加载";
    
    // 点击搜索时 取消键盘响应
    [self.mySearchBar resignFirstResponder];
}


#pragma mark - UITableViewDelegate协议方法实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"热门搜索";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        
        if (_searchHistoryArray.count>0) {
            return _searchHistoryArray.count + 1 + 1;
        }else{
            return 1;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        
        YHY_MyPageSearch_TVC *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MypageSearchTableViewCell"];
        cell.backgroundColor = [UIColor redColor];
        cell.dataSource = _dataSource;
        return cell;
    }else {
        if(indexPath.row ==0){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"历史搜索记录";
            cell.textLabel.textColor = fontCOLOR;
            return cell;
        }else if (indexPath.row == _searchHistoryArray.count + 1){
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            cell.textLabel.text = @"清除历史记录";
            cell.textLabel.textColor = fontCOLOR;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            return cell;
        }else{
            UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"cell"];
            NSArray* reversedArray = [[_searchHistoryArray reverseObjectEnumerator] allObjects];
            cell.textLabel.text = reversedArray[indexPath.row - 1];
            return cell;
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 150;
    }else {
        
        return 40;
    }
}

#pragma mark - 数据解析

- (void)dataRequest {
    [TTMusicAFNetworkTool GETNetWithUrl:@"http://api.dongting.com/misc/sug/billboard?v=v8.4.1.2016032512&alf=alf702006&s=s200&size=20&hid=6518303829743017&tid=0&utdid=VfjPsN6N7esDAFG9M0qbxE1S&uid=867992029051448&f=f3030&net=2&app=ttpod&imsi=460025418172304" body:nil headerFile:nil response:TTMusicJSON success:^(id result) {
        
        for (NSDictionary *dic in result[@"data"]) {
            DataModel *dataModel = [[DataModel alloc] init];
            [dataModel setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:dataModel];
            
        }
        [_tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}
- (void)readNSUserDefaults{
    //取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *searchHistoryArray = [userDefaultes arrayForKey:@"CPYSearchHistoryArray"];
    self.searchHistoryArray = searchHistoryArray;
    [self.tableView reloadData];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
    }
    else if (indexPath.row == _searchHistoryArray.count + 1) {
        //清除所有历史记录
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
        
        //@“ UIAlertControllerStyleAlert，改成这个就是中间弹出"
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [CPYSearchHistoryManager removeAllArray];
            _searchHistoryArray = nil;
            [self.tableView reloadData];
        }];
        //            UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:cancelAction];
        [alertController addAction:deleteAction];
        //            [alertController addAction:archiveAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        MySearchDetailViewController *searchDetailVC = [[MySearchDetailViewController alloc] init];
        NSArray *searchlist = [[_searchHistoryArray reverseObjectEnumerator] allObjects];
        searchDetailVC.str = searchlist[indexPath.row - 1];
        [self.mySearchBar resignFirstResponder];// 放弃第一响应者
        [self.navigationController pushViewController:searchDetailVC animated:YES];
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
